// api/src/middleware/behaviorCollector.js
import recommendationClient from "../utils/recommendationClient";

/**
 * 用户行为收集中间件
 */
const behaviorCollector = (req, res, next) => {
  res.on("finish", () => {
    // 请求成功 & 用户已登录
    if (res.statusCode >= 200 && res.statusCode < 300 && req.user) {
      const userId = req.user._id.toString();
      // 获取原始URL路径
      const originalPath = req.originalUrl.split("?")[0];
      console.log("开始收集用户行为:", {
        userId,
        path: originalPath,
        method: req.method,
        statusCode: res.statusCode,
        user: req.user ? "已登录" : "未登录",
      });

      const behavior = extractBehavior(req, userId, originalPath);

      if (behavior) {
        console.log("收集到用户行为:", behavior);
        recommendationClient
          .recordUserBehavior(behavior)
          .then(() => console.log("行为记录成功"))
          .catch((err) => {
            console.error("记录行为失败:", err);
          });
      } else {
        console.log("未匹配到有效行为");
      }
    } else {
      console.log("跳过行为收集:", {
        statusCode: res.statusCode,
        hasUser: !!req.user,
      });
    }
  });

  next();
};

/**
 * 从请求中提取行为数据
 * @param {Object} req - 请求对象
 * @param {string} userId - 用户ID
 * @param {string} path - 原始URL路径
 * @returns {Object|null} - 行为数据或null
 */
const extractBehavior = (req, userId, path) => {
  const { method } = req;
  console.log("分析请求:", { method, path });

  // 种子详情页浏览
  const torrentViewMatch = /^\/torrent\/info\/([a-zA-Z0-9]+)$/.exec(path);
  if (method === "GET" && torrentViewMatch) {
    console.log("匹配到浏览行为");
    return {
      userId,
      torrentId: torrentViewMatch[1],
      type: "VIEW",
      timestamp: new Date(),
      context: {
        referrer: req.headers.referer || "",
        device: req.headers["user-agent"] || "",
      },
    };
  }

  // 种子下载
  const torrentDownloadMatch = /^\/torrent\/download\/([a-zA-Z0-9]+)\/.+$/.exec(
    path
  );
  console.log("下载匹配结果:", {
    path,
    match: torrentDownloadMatch,
    method,
    isGet: method === "GET",
  });

  if (method === "GET" && torrentDownloadMatch) {
    console.log("匹配到下载行为");
    return {
      userId,
      torrentId: torrentDownloadMatch[1],
      type: "DOWNLOAD",
      timestamp: new Date(),
      context: {
        referrer: req.headers.referer || "",
        device: req.headers["user-agent"] || "",
      },
    };
  }

  // 种子点赞
  const torrentLikeMatch = /^\/torrent\/vote\/([a-zA-Z0-9]+)\/up$/.exec(path);
  if (method === "POST" && torrentLikeMatch) {
    console.log("匹配到点赞行为");
    return {
      userId,
      torrentId: torrentLikeMatch[1],
      type: "LIKE",
      timestamp: new Date(),
      context: {
        referrer: req.headers.referer || "",
        device: req.headers["user-agent"] || "",
      },
    };
  }

  // 搜索行为
  if (
    method === "GET" &&
    path.startsWith("/torrent/search") &&
    req.query.query
  ) {
    console.log("匹配到搜索行为");
    return {
      userId,
      type: "SEARCH",
      timestamp: new Date(),
      context: {
        query: req.query.query,
        device: req.headers["user-agent"] || "",
      },
    };
  }

  return null;
};

export default behaviorCollector;
